var MachineRepairForm = function () {
  var formatUserList = function (userObj, userList) {
    for (var i = 0; i < userList.length; i++) {
      var user = userList[i];
      var children = user.children;
      if (children) {
        formatUserList(userObj, children);
      } else {
        userObj[user.name] = user;
      }
    }
  };

  var MachineFormModel = function (machine, userList) {
    BaseModel.call(this);

    var userObj = {};
    formatUserList(userObj, userList);

    var self = this;
    var fn = {
      initData: function (machine) {
        if (machine === null) {
          machine = {
            status: 1,
            districtCode: []
          };
        }

        var fields = ['id', 'machineModel', 'machineSerialNo', 'outTime', 'buyer', 'status', 'orderNo', 'factoryNo',
          'internetThingsCard', 'typeName'
        ];
        self.setDataFromObj(machine, fields);

        var serviceManager = machine.serviceManager;
        if (SysUtil.isEmpty(serviceManager)) {
          serviceManager = [];
        } else {
          serviceManager = serviceManager.split(',');
        }
        self.serviceManager = this.getUserData(serviceManager);

        var serviceWorker = machine.serviceWorker;
        if (SysUtil.isEmpty(serviceWorker)) {
          serviceWorker = [];
        } else {
          serviceWorker = serviceWorker.split(',');
        }
        self.serviceWorker = this.getUserData(serviceWorker);

        self.address = machine.districtCode;
      },

      getUserData: function (userNameList) {
        var userList = [];
        for (var i = 0; i < userNameList.length; i++) {
          var userName = userNameList[i];
          var obj = userObj[userName];
          if (obj === undefined) {
            continue;
          }

          var userData = [];
          if (obj.dept) {
            userData.push(obj.dept);
          }
          userData.push(obj.name);

          userList.push(userData);
        }
        return userList;
      }
    };

    this.checkValid = function () {
      var fields = ['machineModel', 'machineSerialNo', 'outTime', 'buyer', 'serviceManager', 'serviceWorker'];
      return CheckVaildUtil.checkNullField(fields, this);
    };

    this.getObject = function (addressCodeMap) {
      var postData = {};
      var id = this.id;
      if (!SysUtil.isEmpty(id)) {
        postData.id = id;
      }

      var fields = ['machineModel', 'machineSerialNo', 'buyer', 'status', 'orderNo', 'internetThingsCard', 'typeName'];
      this.setPostData(postData, fields);

      var outTime = this.outTime;
      postData.outTime = moment(outTime).format('YYYY-MM-DD');

      var serviceManager = this.serviceManager;
      serviceManager = _.map(serviceManager, function (manager) {
        return manager[manager.length - 1];
      });
      postData.serviceManager = serviceManager.join(',');

      var serviceWorker = this.serviceWorker;
      serviceWorker = _.map(serviceWorker, function (worker) {
        return worker[worker.length - 1];
      });
      postData.serviceWorker = serviceWorker.join(',');

      var districtCode = this.address;
      var districtName = _.map(districtCode, function (code) {
        return addressCodeMap[code];
      });
      postData.districtName = districtName.join(',');
      postData.districtCode = districtCode.join(',');

      return postData;
    };

    fn.initData(machine);
  };

  var template = /* html */ `
    <div class="machine-repair-form" v-loading.fullscreen.lock="loading">
      <template v-if="machineForm!==null">
        <el-form label-width="auto" size="medium">
          <el-form-item required label="设备型号">
            <el-input v-model="machineForm.machineModel" class="form-input"></el-input>
          </el-form-item>
          <el-form-item required label="设备编号">
            <el-input v-model="machineForm.machineSerialNo" class="form-input"></el-input>
          </el-form-item>
          <el-form-item label="位置">
            <el-cascader clearable filterable v-model="machineForm.address" class="form-input" :options="addressList" separator="-"
              :props="addressProps"></el-cascader>
          </el-form-item>
          <el-form-item label="订单编号">
            <filter-select clearable :options="orderList" v-model="machineForm.orderNo" class="form-input" value-field="orderId" label-field="orderId"
              :pageSize="20" :filter-method="orderFilterMehod">
              <template slot="item" slot-scope="scope">
                <div class="repair-order-select-item">
                  <span style="width:145px;">{{scope.option.orderId}}</span>
                  <span style="min-width:145px;">{{scope.option.companyOrderId}}</span>
                  <span style="min-width:100px;">{{scope.option.factoryId}}</span>
                </div>
              </template>
            </filter-select>
          </el-form-item>
          <el-form-item required label="出厂日期">
            <el-date-picker v-model="machineForm.outTime" class="form-input" value-format="timestamp" :editable="false"></el-date-picker>
          </el-form-item>
          <el-form-item required label="客户">
            <el-input v-model="machineForm.buyer" class="form-input"></el-input>
          </el-form-item>
          <el-form-item required label="维修主管">
            <el-cascader filterable v-model="machineForm.serviceManager" class="form-input" :options="userList" :props="userProps"
              :show-all-levels="false" separator="-"></el-cascader>
          </el-form-item>
          <el-form-item required label="维修技工">
            <el-cascader filterable v-model="machineForm.serviceWorker" class="form-input" :options="userList" :props="userProps"
              :show-all-levels="false" separator="-"></el-cascader>
          </el-form-item>
          <el-form-item label="物联网卡编号">
            <el-input v-model="machineForm.internetThingsCard" class="form-input"></el-input>
          </el-form-item>
          <el-form-item label="警报类型">
            <el-select filterable clearable v-model="machineForm.typeName" class="form-input">
              <el-option v-for="alarmType in alarmTypeList" :key="'alarmType_'+alarmType" :value="alarmType"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否启用">
            <el-select v-model="machineForm.status" class="form-input">
              <el-option v-for="status in statusList" :key="'status_'+status.value" :value="status.value"
                :label="status.label"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div style="text-align:center">
          <el-button size="medium" type="primary" @click="ensure">
            <span v-if="type==='add'">新增</span>
            <span v-else>修改</span>
          </el-button>
        </div>
      </template>
    </div>
  `;

  return {
    props: {
      machine: {
        type: Object,
        default: function () {
          return null;
        }
      },

      type: {
        type: String,
        default: 'add'
      },

      dropdownOption: {
        type: Object,
        defualt: function () {
          return {};
        }
      }
    },

    data: function () {
      return {
        loading: false,
        machineForm: null,
        orderList: [],
        userList: [],
        alarmTypeList: [],
        addressList: [],
        addressCodeMap: null,
        statusList: i18n.getDropDown('machineRepair.repairMgr.status', [1, 0]),
        userProps: {
          multiple: true,
          value: 'name',
          label: 'name'
        },
        addressProps: {
          checkStrictly: true,
          value: 'code',
          label: 'name'
        }
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.setOrderList(),
        this.setUserList(),
        this.setAlarmTypeList(),
        this.setAddressList()
      ]).then(function () {
        self.machineForm = new MachineFormModel(self.machine, self.userList);
        self.loading = false;
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      setOrderList: function () {
        var dropdownOption = this.dropdownOption;
        var orderList = dropdownOption.orderList;
        if (orderList !== undefined) {
          this.orderList = orderList;
          return Promise.resolve(orderList);
        }

        var self = this;
        return ajaxRequest('workOrder/getOrderTree', {
          q: ''
        }).then(function (res) {
          var orderList = res.rows;
          orderList = _.map(orderList, function (order) {
            var orderId = order.id;
            var factoryId = order.text;
            var companyOrderId = order.companyOrderNo;
            return {
              orderId: orderId ? orderId : '',
              factoryId: factoryId ? factoryId : '',
              companyOrderId: companyOrderId ? companyOrderId : ''
            };
          });
          self.orderList = orderList;
          dropdownOption.orderList = orderList;
          return orderList;
        });
      },

      setUserList: function () {
        var dropdownOption = this.dropdownOption;
        var userList = dropdownOption.userList;
        if (userList !== undefined) {
          this.userList = userList;
          return Promise.resolve(userList);
        }

        var self = this;
        return ajaxRequest('workOrder/getCompanyUserTree').then(function (res) {
          var userList = res.rows;

          var userGroup = _.groupBy(userList, function (user) {
            var pid = user.pid;
            if (pid === undefined) {
              return '';
            }
            return pid;
          });

          var users = [];
          for (var key in userGroup) {
            if (key !== '') {
              var obj = {
                name: key
              };
              var children = self.getGroupUsers(userGroup[key]);
              obj.children = children;
              users.push(obj);
            } else {
              var groupUsers = self.getGroupUsers(userGroup[key]);
              users.pushArray(groupUsers);
            }
          }
          users = _.orderBy(users, [function (user) {
            var children = user.children;
            return children ? 0 : 1;
          }], ['asc']);
          self.userList = users;
          dropdownOption.userList = users;
          return users;
        });
      },

      setAlarmTypeList: function () {
        var dropdownOption = this.dropdownOption;
        var alarmTypeList = dropdownOption.alarmTypeList;
        if (alarmTypeList !== undefined) {
          this.alarmTypeList = alarmTypeList;
          return Promise.resolve(alarmTypeList);
        }

        var self = this;
        return ajaxRequest('workOrder/getEquimentAlarmTypeName').then(function (alarmTypeList) {
          self.alarmTypeList = alarmTypeList;
          dropdownOption.alarmTypeList = alarmTypeList;
          return alarmTypeList;
        });
      },

      setAddressList: function () {
        var dropdownOption = this.dropdownOption;
        var addressList = dropdownOption.addressList;
        if (addressList !== undefined) {
          this.addressList = addressList;
          this.addressCodeMap = dropdownOption.addressCodeMap;
          return Promise.resolve(addressList);
        }

        var self = this;
        return ajaxRequest('workOrder/getDistrict').then(function (addressList) {
          var addressObj = {};
          var addressCodeMap = {};
          for (var i = 0; i < addressList.length; i++) {
            var address = addressList[i];
            addressObj[address.id] = address;
            addressCodeMap[address.code] = address.name;
          }

          var addresses = [];
          for (var id in addressObj) {
            var address = addressObj[id];
            var parentId = address.parentId;
            var parentObj = addressObj[parentId];
            if (parentObj === undefined) {
              addresses.push(address);
              continue;
            }

            var children = parentObj.children;
            if (children === undefined) {
              children = [];
              parentObj.children = children;
            }
            children.push(address);
          }
          self.addressList = addresses;
          self.addressCodeMap = addressCodeMap;
          dropdownOption.addressList = addresses;
          dropdownOption.addressCodeMap = addressCodeMap;

          return addresses;
        });
      },

      getGroupUsers: function (userList) {
        userList = _.map(userList, function (user) {
          var pid = user.pid;
          return {
            id: user.id,
            name: user.text,
            dept: pid ? pid : null
          };
        });
        return userList;
      },

      orderFilterMehod: function (query, option) {
        var filterParams = ['orderId', 'companyOrderId', 'factoryId'];
        for (var i = 0; i < filterParams.length; i++) {
          var filterParam = filterParams[i];
          var value = _.get(option, filterParam, '');
          if (value === null) {
            value = '';
          }
          if (typeof value === 'string') {
            value = value.toLowerCase();
          }
          if (value.indexOf(query) !== -1) {
            return true;
          }
        }
        return false;
      },

      ensure: function () {
        var machineForm = this.machineForm;
        var code = machineForm.checkValid();
        if (code !== '') {
          var msg = i18n.getMsg(`machineRepair.repairMgr.error.${code}`);
          this.$alert(msg, '信息');
          return;
        }

        if (this.type === 'add') {
          this.addMachine(machineForm);
        } else {
          this.updateMachine(machineForm);
        }
      },

      addMachine: function (machineForm) {
        var postData = machineForm.getObject(this.addressCodeMap);

        this.loading = true;
        var self = this;
        ajaxRequest('workOrder/addConfig', postData).then(function () {
          self.loading = false;
          self.$alert('设备新增成功', '信息', {
            callback: function () {
              self.$emit('save-success');
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      updateMachine: function (machineForm) {
        var postData = machineForm.getObject(this.addressCodeMap);

        this.loading = true;
        var self = this;
        ajaxRequest('workOrder/updateConfig', postData).then(function () {
          self.loading = false;
          self.$alert('设备修改成功', '信息', {
            callback: function () {
              self.$emit('save-success');
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      }
    },

    components: {
      FilterSelect: FilterSelect
    },

    template: template
  };
}();
